"""
DeepSeek管理器 - 完全替代Google ADK的实现
"""
import asyncio
import datetime
import json
import os
import uuid
from typing import Any, Dict, List, Optional

import httpx
from openai import AsyncOpenAI

from a2a.types import (
    AgentCard,
    Artifact,
    DataPart,
    FilePart,
    FileWithBytes,
    FileWithUri,
    Message,
    Part,
    Role,
    Task,
    TaskState,
    TaskStatus,
    TextPart,
)

from service.server.application_manager import ApplicationManager
from service.types import Conversation, Event


class DeepSeekManager(ApplicationManager):
    """DeepSeek实现的应用管理器"""

    def __init__(
        self,
        http_client: httpx.AsyncClient,
        api_key: str = '',
    ):
        self._conversations: list[Conversation] = []
        self._messages: list[Message] = []
        self._tasks: list[Task] = []
        self._events: dict[str, Event] = {}
        self._pending_message_ids: list[str] = []
        self._agents: list[AgentCard] = []
        self._context_to_conversation: dict[str, str] = {}
        
        self.user_id = 'test_user'
        self.app_name = 'A2A'
        self.api_key = api_key or os.environ.get('DEEPSEEK_API_KEY', '')
        
        # 初始化DeepSeek客户端
        if self.api_key:
            self.client = AsyncOpenAI(
                api_key=self.api_key,
                base_url="https://api.deepseek.com/v1"
            )
        else:
            self.client = None
            print("警告: 未设置DEEPSEEK_API_KEY")

    def create_conversation(self) -> Conversation:
        """创建新对话"""
        conversation_id = str(uuid.uuid4())
        c = Conversation(conversation_id=conversation_id, is_active=True)
        self._conversations.append(c)
        return c

    def update_api_key(self, api_key: str):
        """更新API密钥"""
        if api_key and api_key != self.api_key:
            self.api_key = api_key
            os.environ['DEEPSEEK_API_KEY'] = api_key
            # 重新初始化客户端
            self.client = AsyncOpenAI(
                api_key=self.api_key,
                base_url="https://api.deepseek.com/v1"
            )

    def sanitize_message(self, message: Message) -> Message:
        """清理消息"""
        return message

    async def process_message(self, message: Message):
        """处理消息并调用DeepSeek API"""
        message_id = message.messageId
        if message_id:
            self._pending_message_ids.append(message_id)
            
        context_id = message.contextId
        conversation = self.get_conversation(context_id)
        self._messages.append(message)
        
        if conversation:
            conversation.messages.append(message)

        # 添加用户事件
        self.add_event(
            Event(
                id=str(uuid.uuid4()),
                actor='user',
                content=message,
                timestamp=datetime.datetime.utcnow().timestamp(),
            )
        )

        try:
            # 调用DeepSeek API
            response_text = await self._call_deepseek_api(message, conversation)
            
            # 创建响应消息
            response_message = Message(
                role=Role.agent,
                parts=[Part(root=TextPart(text=response_text))],
                messageId=str(uuid.uuid4()),
                contextId=context_id,
                taskId=message.taskId,
            )
            
            self._messages.append(response_message)
            if conversation:
                conversation.messages.append(response_message)

            # 添加助手事件
            self.add_event(
                Event(
                    id=str(uuid.uuid4()),
                    actor='deepseek_agent',
                    content=response_message,
                    timestamp=datetime.datetime.utcnow().timestamp(),
                )
            )

        except Exception as e:
            print(f"处理消息时出错: {e}")
            # 创建错误响应
            error_message = Message(
                role=Role.agent,
                parts=[Part(root=TextPart(text=f"抱歉，处理您的请求时出现错误: {str(e)}"))],
                messageId=str(uuid.uuid4()),
                contextId=context_id,
                taskId=message.taskId,
            )
            self._messages.append(error_message)
            if conversation:
                conversation.messages.append(error_message)
        
        finally:
            if message_id in self._pending_message_ids:
                self._pending_message_ids.remove(message_id)

    async def _call_deepseek_api(self, message: Message, conversation: Optional[Conversation] = None) -> str:
        """调用DeepSeek API"""
        if not self.client:
            raise ValueError("DeepSeek客户端未初始化，请检查API密钥")

        # 构建消息历史
        messages = []
        
        # 添加系统提示
        messages.append({
            "role": "system",
            "content": "你是一个有用的AI助手。请用中文回答用户的问题。"
        })
        
        # 添加对话历史（最近10条消息）
        if conversation and conversation.messages:
            recent_messages = conversation.messages[-10:]  # 只取最近10条消息
            for msg in recent_messages[:-1]:  # 排除当前消息
                content = self._extract_text_from_message(msg)
                if content:
                    role = "user" if msg.role == Role.user else "assistant"
                    messages.append({"role": role, "content": content})

        # 添加当前消息
        current_content = self._extract_text_from_message(message)
        if current_content:
            messages.append({"role": "user", "content": current_content})

        # 调用DeepSeek API
        try:
            response = await self.client.chat.completions.create(
                model="deepseek-chat",
                messages=messages,
                max_tokens=2000,
                temperature=0.7,
                stream=False
            )
            
            if response.choices and len(response.choices) > 0:
                return response.choices[0].message.content
            else:
                return "抱歉，我无法生成回复。"
                
        except Exception as e:
            print(f"DeepSeek API调用失败: {e}")
            raise e

    def _extract_text_from_message(self, message: Message) -> str:
        """从消息中提取文本内容"""
        text_parts = []
        if message.parts:
            for part in message.parts:
                if part.root and part.root.kind == 'text':
                    text_parts.append(part.root.text)
                elif part.root and part.root.kind == 'data':
                    # 尝试将数据转换为文本
                    try:
                        data_str = json.dumps(part.root.data, ensure_ascii=False)
                        text_parts.append(f"[数据]: {data_str}")
                    except:
                        text_parts.append("[无法解析的数据]")
        
        return " ".join(text_parts)

    def add_event(self, event: Event):
        """添加事件"""
        self._events[event.id] = event

    def get_conversation(self, conversation_id: str | None) -> Conversation | None:
        """获取对话"""
        if not conversation_id:
            return None
        return next(
            filter(
                lambda c: c and c.conversation_id == conversation_id,
                self._conversations,
            ),
            None,
        )

    def get_pending_messages(self) -> list[tuple[str, str]]:
        """获取待处理消息"""
        return [(msg_id, "处理中...") for msg_id in self._pending_message_ids]

    def register_agent(self, url: str):
        """注册代理"""
        # 为DeepSeek创建一个虚拟的代理卡
        agent_card = AgentCard(
            name="DeepSeek Agent",
            description="DeepSeek AI助手",
            url=url,
            version="1.0.0"
        )
        self._agents.append(agent_card)

    @property
    def agents(self) -> list[AgentCard]:
        """获取代理列表"""
        return self._agents

    @property
    def conversations(self) -> list[Conversation]:
        """获取对话列表"""
        return self._conversations

    @property
    def tasks(self) -> list[Task]:
        """获取任务列表"""
        return self._tasks

    @property
    def events(self) -> list[Event]:
        """获取事件列表"""
        return sorted(self._events.values(), key=lambda x: x.timestamp) 